package com.upbos.sso.entity;

import cn.hutool.core.codec.Base64;
import com.upbos.core.util.RandomUtils;
import com.upbos.sso.Constants;
import com.upbos.sso.exception.SsoExceptionCode;
import com.upbos.sso.exception.SsoException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wangjz
 */
@Data
@Slf4j
public class TokenId {
    private String tokenType;

    private String uid;

    private String sessionId;

    /**
     * tokenId: web_30_3ks321f5
     *
     * @param tokenType
     * @param uid
     * @return
     */
    public static String generate(String tokenType, String uid) {
        if (tokenType == null || tokenType.indexOf(Constants.TOKEN_ID_SPLIT_SIGN) > -1) {
            throw new SsoException(SsoExceptionCode.TOKEN_ID_GENERATE_TYPE);
        }

        if (uid == null || uid.indexOf(Constants.TOKEN_ID_SPLIT_SIGN) > -1) {
            throw new SsoException(SsoExceptionCode.TOKEN_ID_GENERATE_UID);
        }

        StringBuffer tokenId = new StringBuffer(tokenType)
                .append(Constants.TOKEN_ID_SPLIT_SIGN)
                .append(uid)
                .append(Constants.TOKEN_ID_SPLIT_SIGN)
                .append(RandomUtils.getCharacterAndNumber(Constants.TOKEN_ID_RANDOM_NUMBER_LENGTH));
        return Base64.encode(tokenId);
    }

    public static TokenId parse(String tokenId) {
        if (tokenId == null) {
            throw new SsoException(SsoExceptionCode.TOKEN_ID_NULL);
        }

        tokenId = Base64.decodeStr(tokenId);
        String[] tokenIdArray = tokenId.split(Constants.TOKEN_ID_SPLIT_SIGN);
        if (tokenIdArray.length != Constants.TOKEN_ID_PART_LENGTH) {
            log.error("解析tokenId时", new SsoException(SsoExceptionCode.TOKEN_ID_FORMAT));
            return null;
        }

        TokenId tokenIdWrap = new TokenId();
        tokenIdWrap.setTokenType(tokenIdArray[0]);
        tokenIdWrap.setUid(tokenIdArray[1]);
        tokenIdWrap.setSessionId(tokenIdArray[2]);
        return tokenIdWrap;
    }
}
